package com.huike.clues.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.clues.domain.SysDictType;
import com.huike.clues.domain.vo.SysDictTypeVo;
import com.huike.clues.mapper.SysDictTypeMapper;
import com.huike.clues.service.ISysDictTypeService;
import com.huike.common.constant.Constants;
import com.huike.common.core.domain.entity.SysDictTypeDTO;
import com.huike.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author Ls
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Autowired
    private SysDictTypeMapper dictTypeMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 添加字典类型
     *
     * @param dto 字典类型
     */
    @Override
    @Transactional
    public void addType(SysDictTypeDTO dto) {
        SysDictType sysDictType = BeanUtil.toBean(dto, SysDictType.class);
        this.save(sysDictType);
        redisCache.deleteObject(Constants.SYS_DICT_TYPE_KEY);
    }


    /**
     * 修改字典类型
     *
     * @param dto 字典类型
     */
    @Override
    @Transactional
    public void updateType(SysDictTypeDTO dto) {
        SysDictType sysDictType = BeanUtil.toBean(dto, SysDictType.class);
        this.updateById(sysDictType);
        redisCache.deleteObject(Constants.SYS_DICT_TYPE_KEY);
    }

    /**
     * 清空缓存
     */
    @Override
    public void clearCache() {
        Collection<String> keys = redisCache.keys(Constants.SYS_DICT_KEY + "*");
        redisCache.deleteObject(keys);
    }

    /**
     * 查询字典类型列表
     *
     * @param dto 字典类型
     * @return 字典类型列表
     */
    @Override
    public List<SysDictTypeVo> selectDictTypeList(SysDictTypeDTO dto) {
        return dictTypeMapper.selectDictTypeList(dto);
    }

    /**
     * 字典下拉列表
     *
     * @return 字典类型列表
     */
    @Override
    @Transactional
    public List<SysDictType> optionSelect() {
        List<SysDictType> list = redisCache.getCacheList(Constants.SYS_DICT_TYPE_KEY);
        if (CollectionUtil.isNotEmpty( list)){
            return list;
        }
         list = this.list();
        redisCache.setCacheList(Constants.SYS_DICT_TYPE_KEY, list);
        return list;
    }

    /**
     * 批量删除字典类型
     *
     * @param dictIds 字典类型ID
     */
    @Override
    @Transactional
    public void removeByIds(String dictIds) {
        String[] ids= dictIds.split(",");
        this.removeByIds(Arrays.asList(ids));
        redisCache.deleteObject(Constants.SYS_DICT_TYPE_KEY);
    }
}
